#include"SListNode.h"
void SListPrint(SListNode* plist)
{
	SListNode* pcur = plist;
	while (pcur)
	{
		printf(" %d -> ", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}

SListNode* BuySListNode(SLTDateType x)
{
	SListNode* newnode = (SListNode*)malloc(sizeof(SListNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(1);
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}
void SListPushBack(SListNode** pplist, SLTDateType x)
{
	SListNode* newnode = BuySListNode(x);
	if (*pplist == NULL)
	{
		*pplist = newnode;
	}
	else {
		SListNode* ptail = *pplist;
		while (ptail->next)
		{
			ptail = ptail -> next;
		}
		ptail->next = newnode;
	}
}

void SListPushFront(SListNode** pplist, SLTDateType x)
{
	SListNode* newnode = BuySListNode(x);
	if(*pplist == NULL)
	{
		*pplist = newnode;
	}
	else {
		SListNode* phead = *pplist;
		newnode->next = phead;
		*pplist = newnode;
	}
}

void SListPopBack(SListNode** pplist)
{
	assert(pplist && *pplist);
	SListNode* ptail = *pplist;
	SListNode* pre = NULL;
	while (ptail->next)
	{
		pre = ptail;
		ptail = ptail->next;
	}
	pre->next = NULL;
	free(ptail);
	ptail = NULL;
}

void SListPopFront(SListNode** pplist)
{
	assert(pplist && *pplist);
	SListNode* phead = *pplist;
	*pplist = phead->next;
}

SListNode* SListFind(SListNode* plist, SLTDateType x)
{
	assert(plist);
	SListNode* ptail = plist;
	while (ptail->next)
	{
		if (ptail->data == x)
		{
			return ptail;
		}
		ptail = ptail->next;
	}
	return NULL;
}

void SListInsertAfter(SListNode* pos, SLTDateType x)
{
	assert(pos);
	SListNode* newnode = BuySListNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}

void SListEraseAfter(SListNode* pos)
{
	assert(pos);
	SListNode* pcur = pos->next;
	if (pcur == NULL)
		pos->next = NULL;
	pos->next = pcur->next;
	free(pcur);
	pcur = NULL;
}

void SLTInsert(SListNode** pphead, SListNode* pos, SLTDateType x)
{
	assert(*pphead && pos);
	SListNode* prev = *pphead;
	
	if (prev == pos)
	{
		SListPushFront(*pphead, x);
	}
	else {
		SListNode* newnode = BuySListNode(x);
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = newnode;
		newnode->next = pos;
	}
}

void SLTErase(SListNode** pphead, SListNode* pos)
{
	assert(*pphead && pos);
	SListNode* prev = *pphead;
	while (prev->next != pos)
	{
		prev = prev->next;
	}
	prev->next = pos->next;
}

void SLTDestroy(SListNode** pphead)
{
	assert(*pphead);
	SListNode* pcur = *pphead;
	while (pcur)
	{
		SListNode* next = pcur->next;
		free(pcur);
		pcur = next;
	}
	*pphead = NULL;
}